package cn.edu.swu.lxy.rolems.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.edu.swu.lxy.rolems.activity.MainActivity
import cn.edu.swu.lxy.rolems.R
import cn.edu.swu.lxy.rolems.adapter.LoveAdapter
import cn.edu.swu.lxy.rolems.Role
import cn.edu.swu.lxy.rolems.MyDatabaseHelperRole

class LoveFragment: Fragment() {
    private val itemList = ArrayList<Role>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val view = View.inflate(activity, R.layout.fragment_love, null)
        val dbHelper: MyDatabaseHelperRole = MyDatabaseHelperRole(activity as MainActivity, "Roles.db", 2)
        initItems(dbHelper) // 初始化数据
        val layoutManager = LinearLayoutManager(activity)
        layoutManager.orientation = LinearLayoutManager.VERTICAL
        val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.layoutManager = layoutManager
        val adapter = LoveAdapter(activity as MainActivity, itemList)
        recyclerView.adapter = adapter

        return view
    }

    @SuppressLint("Range")
    private fun initItems(dbHelper: MyDatabaseHelperRole) {
        itemList.clear()
        val db = dbHelper.writableDatabase
        val cursor = db.query("MyRoles", null, null, null, null, null, null)
        if (cursor.moveToFirst()) {
            do {
//                   遍历Cursor对象，取出数据并打印
                val name = cursor.getString(cursor.getColumnIndex("name"))
                val attr = cursor.getString(cursor.getColumnIndex("attr"))
                val ps = cursor.getString(cursor.getColumnIndex("ps"))
                val pic = cursor.getInt(cursor.getColumnIndex("pic"))
                itemList.add(Role(name, pic, attr, ps))
            } while (cursor.moveToNext())
        }
    }
}